﻿using Nancy;
using Nancy.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using YYBlog.Core;
using YYBlog.Core.Commands.Accounts;
using YYBlog.Core.ViewProjections.Admin;

namespace YYBlog.Web.Modules
{
    public class AdminModule : SecureModule
    {
        private readonly ICommandInvokerFactory _commandInvokerFactory;
        public AdminModule(ICommandInvokerFactory commandInvokerFactory, IViewProjectionFactory viewProjectionFactory) : base(viewProjectionFactory)
        {
            _commandInvokerFactory = commandInvokerFactory;

            Get["/yy-admin/index"] = _ => Index();

            Get["/yy-admin/change-password"] = _ => ChangePassword();
            Post["/yy-admin/change-password"] = _ => ChangePassword(this.Bind<ChangePasswordCommand>());

            Get["/yy-admin/change-profile"] = _ => ChangeProfile();
            Post["/yy-admin/change-profile"] = _ => ChangeProfile(this.Bind<ChangeProfileCommand>());
        }

        private dynamic ChangePassword()
        {
            return View["ChangePassword"];
        }

        private dynamic ChangePassword(ChangePasswordCommand command)
        {
            var commandResult = _commandInvokerFactory.Handle<ChangePasswordCommand, CommandResult>(command);

            if (commandResult.Success)
            {
                AddMessage("密码已经被成功修改", "success");

                return View["ChangePassword"];
            }

            AddMessage("修改密码过程中发生问题", "warning");

            return View["ChangePassword"];
        }

        private dynamic ChangeProfile()
        {
            var authorModel = _viewProjectionFactory.Get<string, AuthorProfileViewModel>(CurrentUser.Id);
            return View["ChangeProfile", authorModel];
        }

        private dynamic ChangeProfile(ChangeProfileCommand command)
        {
            var commandResult = _commandInvokerFactory.Handle<ChangeProfileCommand, CommandResult>(command);

            if (commandResult.Success)
            {
                return Response.AsRedirect("/yy-admin/index");
            }

            AddMessage("修改用户信息过程中发生问题", "warning");

            return View["ChangeProfile"];
        }

        private dynamic Index()
        {
            return View["Index"];
        }
    }
}